package com.cjr.ddp.configuration;

import com.alibaba.fastjson.JSONObject;
import com.cjr.ddp.util.ReturnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author cjr
 * @date Created in 2020-03-05 23:01
 * @description 自定义拦截器
 * @modified By
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag;
        ReturnMsg msg = new ReturnMsg();
        String tokenParam = request.getParameter("token");
        System.out.println(tokenParam);
        if (tokenParam == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            msg.setSuccess(false);
            msg.setCode("403");
            msg.setContent("鉴权码无效，请重新登录！");
            String returnMsg = JSONObject.toJSONString(msg);
            out.append(returnMsg);
            flag = false;
        } else if (!redisTemplate.hasKey(tokenParam)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            msg.setSuccess(false);
            msg.setCode("403");
            msg.setContent("用户未登录或登录过时，请登录后操作！");
            String returnMsg = JSONObject.toJSONString(msg);
            out.append(returnMsg);
            flag = false;
        } else {
            flag = true;
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
